import React, { useRef, useState } from "react";
import { Form, Input, Button, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { history } from "umi";

import { FormInstance } from "antd";
import { login, singleUpload } from "@/services";
import FileUploader from "@/utils/uploader";
import styles from "./index.less";

interface UploadStatus {
  progress: number;
  isUploading: boolean;
  error: string | null;
}
interface UploadMessage {
  type: "progress" | "chunk-success" | "chunk-error" | "upload-complete";
  index?: number;
  progress?: number;
  hash?: string;
  error?: Error;
}

const DashboardPage = () => {
  const [status, setStatus] = useState<UploadStatus>({
    progress: 0,
    isUploading: false,
    error: null,
  });

  const fileInputRef = useRef<HTMLInputElement>(null);
  const uploaderRef = useRef<FileUploader | null>(null);
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setStatus((prev) => ({ ...prev, isUploading: true, error: null }));

    // 初始化上传器
    uploaderRef.current = new FileUploader(file);

    // 监听进度更新
    // uploaderRef.current.setupWorkerCommunication = (worker: any) => {
    //   console.log(worker);

    //   worker.onmessage = (e: MessageEvent<UploadMessage>) => {
    //     if (e.data.type === "progress") {
    //       setStatus((prev) => ({ ...prev, progress: e.data.progress! }));
    //     } else if (e.data.type === "upload-complete") {
    //       setStatus((prev) => ({ ...prev, isUploading: false, progress: 100 }));
    //     }
    //   };
    // };

    uploaderRef.current.start();
  };

  const handlePause = () => {
    uploaderRef.current?.pause();
    setStatus((prev) => ({ ...prev, isUploading: false }));
  };

  const handleResume = () => {
    uploaderRef.current?.resume();
    setStatus((prev) => ({ ...prev, isUploading: true }));
  };
  return (
    <div>
      <div className="container">
        <h1>Electron 小文件上传 Demo</h1>
        <input type="file" name="" id="fileInput" />
        <Button
          type="primary"
          onClick={() => {
            const fileInput = document.getElementById("fileInput");
            // 检查是否选择了文件
            if (fileInput?.files?.length === 0) {
              alert("请选择文件");
              return;
            }
            // 创建 FormData 对象
            const formData = new FormData();
            // 将文件添加到 FormData（字段名 'file' 需与后端匹配）
            formData.append("file", fileInput?.files?.[0]);
            singleUpload(formData);
          }}
        >
          上传文件
        </Button>
      </div>

      <div className="container">
        <h1>Electron 大文件上传 Demo</h1>
        <div className="upload-form">
          <input
            type="file"
            ref={fileInputRef}
            onChange={handleFileChange}
            disabled={status.isUploading}
          />

          {/* <button
              onClick={handleUpload}
              disabled={!fileInputRef.current?.files?.[0] || status.isUploading}
            >
              开始上传
            </button> */}

          {status.isUploading && (
            <div className="progress-container">
              <progress value={status.progress} max="100"></progress>
              <span>{status.progress}%</span>

              {status.error && (
                <div className="error-message">
                  <p>{status.error}</p>
                  <button onClick={handlePause}>暂停</button>
                  <button onClick={handleResume}>继续</button>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default DashboardPage;
